package com.mall507.fivepeaks.activity.main;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.fragment.AbsRecyclerViewFM;
import com.hzh.frame.util.AndroidUtil;
import com.hzh.frame.widget.xrecyclerview.BaseRecyclerAdapter;
import com.hzh.frame.widget.xrecyclerview.RecyclerViewHolder;
import com.mall507.comn.model.ChooseBianmin;
import com.mall507.comn.model.ConvenientLifeChuShou;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.widget.imageview.ExpandImageView;
import com.mall507.fivepeaks.widget.xdialog.XRadioGroupDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 便民列表 | 出售
 */
public class MainConvenientLifeChuShouRFM extends AbsRecyclerViewFM<ConvenientLifeChuShou> {

    LinearLayout screens;
    List<TextView> screenSelectList = new ArrayList<>();
    private PopupWindow chooseWindow;
    private View chooseView;

    public static MainConvenientLifeChuShouRFM newInstance(int type) {
        MainConvenientLifeChuShouRFM myFragment = new MainConvenientLifeChuShouRFM();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        myFragment.setArguments(bundle);
        return myFragment;
    }

    @Override
    public boolean setTitleIsShow() {
        return false;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fm_rv_main_convenient_life;
    }

    @Override
    protected void bindView(View view) {
        showLoding();
        screens = view.findViewById(R.id.screens);
        setLoadPattern(1);
        findType();
        chooseView = getActivity().getLayoutInflater().inflate(R.layout.view_window_spinner, null);
        chooseWindow = new PopupWindow(chooseView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        chooseWindow.setFocusable(true);
        chooseWindow.setBackgroundDrawable(new BitmapDrawable());
    }


    /**
     * 查询分类数据
     */
    public void findType() {
        JSONObject params = new JSONObject();
        try {
            params.put("catid", getArguments().getInt("type"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query("release/getNavPar", params,new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")) {
                    JSONArray list = response.optJSONArray("data");
                    if (list != null && list.length() > 0) {
                        screens.removeAllViews();
                        int itemWidth = AndroidUtil.getWindowWith() / list.length();
                        for (int i = 0; i < list.length(); i++) {
                            JSONObject object = list.optJSONObject(i);
                            LinearLayout screen = (LinearLayout) getLayoutInflater().inflate(R.layout.include_layout_screen_item, null);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(itemWidth, LinearLayout.LayoutParams.MATCH_PARENT);
                            screen.setLayoutParams(lp);
                            screen.setOrientation(LinearLayout.HORIZONTAL);
                            screen.setBackgroundResource(R.drawable.item_lv_store_main_selected);
                            screen.setGravity(Gravity.CENTER);
                            final int m = i;

                            final TextView content = screen.findViewById(R.id.content);
                            content.setText(object.optString("name"));
                            content.setTag(R.id.main_convenient_life_key, object.optString("key"));
                            content.setTag(R.id.main_convenient_life_value, "0");
                            content.setTag(R.id.main_convenient_life_parent_name, object.optString("name"));
                            content.setTag(R.id.main_convenient_life_parent_key, object.optString("key"));
                            screenSelectList.add(content);

                            JSONArray itemArray = object.optJSONArray("item");
                            final List<HashMap<String, Object>> radioGroupList = new ArrayList<>();
                            final List<ChooseBianmin> bianmins = new ArrayList<ChooseBianmin>();
                            for (int j = 0; j < itemArray.length(); j++) {
                                JSONObject itemObj = itemArray.optJSONObject(j);
                                ChooseBianmin model = new ChooseBianmin();
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("name", itemObj.optString("name"));
                                map.put("value", itemObj.optString("id"));
                                model.setStrname(itemObj.optString("name"));
                                model.setNid(itemObj.optString("id"));
                                bianmins.add(model);
                                radioGroupList.add(map);
                                if(j==0){//设置默认值,默认第一个为需要请求的值
                                    content.setText(map.get("name").toString());
                                    content.setTag(R.id.main_convenient_life_value, itemObj.optString("id"));
                                }
                            }
                            screen.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    int n = m;
                                    setChooseWindow(bianmins,radioGroupList,screenSelectList,n);
                                }
                            });
                            screens.addView(screen);
                        }
                        setLoadPattern(2);
                        loadData();
                        screens.setVisibility(View.VISIBLE);
                    } else {
                        screens.setVisibility(View.GONE);
                    }
                }
                dismissLoding();
            }
        });
    }

    @Override
    protected String setHttpPath() {
        return "release/releaseList";
    }

    @Override
    protected JSONObject setHttpParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("catid", getArguments().getInt("type"));
            for (int i = 0; i < screenSelectList.size(); i++) {
                TextView textView = screenSelectList.get(i);
                String key = textView.getTag(R.id.main_convenient_life_key).toString();
                String value = textView.getTag(R.id.main_convenient_life_value).toString();
                params.put(key, value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    @Override
    protected List<ConvenientLifeChuShou> handleHttpData(JSONObject response) {
        List<ConvenientLifeChuShou> list = new ArrayList<ConvenientLifeChuShou>();
        if (200 == response.optInt("code")) {
            JSONArray listJson = response.optJSONArray("data");
            if (listJson != null && listJson.length() > 0) {
                for (int i = 0; i < listJson.length(); i++) {
                    JSONObject obj = listJson.optJSONObject(i);
                    ConvenientLifeChuShou model = new ConvenientLifeChuShou();
                    model.setNid(obj.optString("id"));
                    model.setIcon(obj.optString("thumb"));
                    model.setTitle(obj.optString("title"));
                    model.setXiaoqu(obj.optString("xiaoqu"));
                    model.setShi(obj.optString("shi"));
                    model.setShi(obj.optString("shi"));
                    model.setTing(obj.optString("ting"));
                    model.setWei(obj.optString("wei"));
                    model.setMianji(obj.optString("mianji"));
                    model.setMoney(obj.optString("price"));
                    model.setTime(obj.optString("posttime"));
                    list.add(model);
                }
            }
        }
        dismissLoding();
        return list;
    }

    @Override
    protected void handleHttpDataFailure() {
        super.handleHttpDataFailure();
        showLodingFail();
    }

    @Override
    protected int setItemLayoutId(int viewType) {
        return R.layout.item_rv_main_convenient_life_chu_shou;
    }

    @Override
    protected void bindItemData(RecyclerViewHolder holder, int position, final ConvenientLifeChuShou model) {
        ((ExpandImageView) holder.getView(R.id.icon)).setImageURI(model.getIcon());
        String desc = model.getXiaoqu() + "|" + model.getShi() + "室" + model.getTing()  + "厅" + model.getWei() + "卫"  + "|" + model.getMianji() + "m²";
        holder.setText(R.id.title, model.getTitle());
        holder.setText(R.id.desc, desc);
        holder.setText(R.id.money, model.getMoney() + "万");
        holder.setText(R.id.time, model.getTime());
        holder.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/main/MainChuShouInfoRUI").withString("id", model.getNid()).navigation();
            }
        });
    }

    private void setChooseWindow(List<ChooseBianmin> list, List<HashMap<String, Object>> radioGroupList, List<TextView> screenSelectList, int i){
        chooseWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        chooseWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        chooseWindow.setOutsideTouchable(false);
        chooseWindow.setBackgroundDrawable(new BitmapDrawable());

        //设置显示在哪个控件下面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int[] mLocation = new int[2];
            screens.getLocationInWindow(mLocation);
            int offsetY = mLocation[1] + screens.getHeight();
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight(); // 获取屏幕高度
                chooseWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            chooseWindow.showAtLocation(chooseView, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
            chooseWindow.showAsDropDown(screens);//设置显示在哪个控件下面
        }

        RecyclerView rv = chooseView.findViewById(R.id.choose);
        TextView close = chooseView.findViewById(R.id.close);
        rv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rv.setAdapter(new ChooseAdapter(getActivity(),list,radioGroupList, screenSelectList,i));
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseWindow.dismiss();
            }
        });

    }

    class ChooseAdapter extends BaseRecyclerAdapter<ChooseBianmin> {
        List<HashMap<String, Object>> radioGroupLists;
        List<TextView> screenChoose;
        int j;

        public ChooseAdapter(Context ctx, List<ChooseBianmin> list, List<HashMap<String, Object>> radioGroupList, List<TextView> screenSelectList, int i) {
            super(ctx, list);
            radioGroupLists = radioGroupList;
            screenChoose = screenSelectList;
            j = i;
        }

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.item_window_spinner;
        }

        @Override
        public void bindData(RecyclerViewHolder holder, final int position, final ChooseBianmin item) {
            final CheckBox checkBox = holder.itemView.findViewById(R.id.chooseText);
            checkBox.setText(item.getStrname());
            checkBox.setTag(R.id.main_convenient_life_value,item.getNid());
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    chooseWindow.dismiss();
                    screenChoose.get(j).setText(item.getStrname());
                    screenChoose.get(j).setTag(R.id.main_convenient_life_value, radioGroupLists.get(position).get("value").toString());
                    setLoadPattern(2);
                    loadData();


                }
            });
        }

        @Override
        //重写此方法可实现动态设置每个item项在行、列中所占的份数
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            //设置占领全部空间
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        }

    }

}
